// history.js
import requestAPI from '../../utils/requestApi'; // 确保路径正确

Component({
  options: {
    // 组件的附加选项
  },

  properties: {
    // 组件属性
  },

  data: {
    word: 'word',
    wordop: [
      {text: '历史浏览', value: 'word'}
    ],
    segmentOptions: [
      { text: '景点', value: 'scenic' },
      { text: '美食', value: 'food' },
      { text: '活动', value: 'active'},
    ],
    activeTab: 'scenic', // 默认显示景点
    historyList: [], // 历史记录列表
    loading: false
  },

  lifetimes: {
    // 组件生命周期
    onShow() {
      // 组件实例进入页面节点树时执行
      this.fetchHistory('scenic'); // 默认加载景点历史
    },
    
  },

  methods: {
    // 切换标签
    onChangeSegment(event) {
      this.setData({
        activeTab: event.detail,
      });
      console.log('Component is attached');
      this.fetchHistory(); // 切换时加载对应的历史记录
    },

    // 加载历史记录
    fetchHistory() {
      const userKey = wx.getStorageSync('userKey') || 'default_userKey';
      const type = this.data.activeTab;
      const url = `/travel/history/list?userKey=${userKey}&type=${type}`;

      this.setData({ loading: true }); // 设置加载状态

      requestAPI.get(url).then(res => {
        if (res.code === 200 && res.data) {
          // console.log(res);
          const data = res.data.map(item =>({
            id: item.itemId,
            name:item.name,
            images:item.images,
            type: item.type === 'scenic' ? '景点' : item.type === 'food' ? '美食' : item.type === 'active' ? '活动' : '',
          }))

          this.setData({
            historyList: data,
            loading: false
          });
        } else {
          this.setData({
            historyList: [],
            loading: false
          });
          wx.showToast({
            title: '暂无历史记录',
            icon: 'none',
            duration: 2000,
          });
        }
      }).catch(error => {
        console.error('请求历史记录数据失败:', error);
        this.setData({
          loading: false
        });
        wx.showToast({
          title: '请求失败，请稍后再试',
          icon: 'none',
          duration: 2000,
        });
      });
    },

    // 跳转到详情页面
    navigateToDetail(event) {
      const id = event.currentTarget.dataset.id;
      if (this.data.activeTab === 'scenic') {
        wx.navigateTo({
          url: `/pages/scenicIntroduction/scenicIntroduction?id=${id}`,
        });
      } else if (this.data.activeTab === 'food') {
        wx.navigateTo({
          url: `/pages/foodDetail/foodDetail?id=${id}`,
        });
      } else if (this.data.activeTab === 'active') {
        wx.navigateTo({
          url: `/pages/active-detail/active-detail?id=${id}`,
        });
      }
    },
  }
});